package cn.com.busi.web.ctl;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;



import cn.com.base.sys.common.Page;
import cn.com.base.sys.common.Result;
import cn.com.base.sys.security.SessionManager;
import cn.com.base.sys.util.Strings;
import cn.com.busi.model.InfoImages;
import cn.com.busi.model.InfoNews;
import cn.com.busi.model.InfoProduct;
import cn.com.busi.model.InfoProductImage;
import cn.com.busi.model.InfoProductType;
import cn.com.busi.service.InfoImagesService;
import cn.com.busi.service.InfoNewsService;
import cn.com.busi.service.InfoProductImageService;
import cn.com.busi.service.InfoProductService;
import cn.com.busi.service.InfoProductTypeService;
import cn.com.busi.service.impl.InfoImagesServiceImpl;
import cn.com.busi.web.vo.InfoImagesRS;
import cn.com.busi.web.vo.InfoImagesReq;
import cn.com.weixin.sdk.api.ApiResult;
import cn.com.weixin.sdk.api.MediaApi;
/**
 *InfoImages 的控制类
 */
@Controller
@RequestMapping("/admin")
public class InfoImagesCtl  extends SessionManager{
    static Logger log=Logger.getLogger(InfoImagesCtl.class);
	@Autowired
	/**
	 *InfoImages逻辑操作接口
	 */
	private InfoImagesService infoImagesService;
	/**
	 *InfoImages分页查询
	 */
	@RequestMapping("/infoImagesQuery")
	public ModelAndView  infoImagesQuery(@ModelAttribute InfoImagesReq infoImagesReq, HttpServletRequest request,HttpServletResponse response, ModelMap modelMap){
		//super.adminLoginValidate(request);
		InfoImagesRS infoImagesRS=infoImagesReq.getInfoImagesRS();
		modelMap.put("pageSize",infoImagesReq.getPageSize());
		modelMap.put("pageNo", infoImagesReq.getPageNo());
		modelMap.put("ctx", request.getContextPath());
		modelMap.put("infoImagesRS", infoImagesRS);
		Page<InfoImages> page=infoImagesService.findInfoImagesByPage(infoImagesReq.getPageNo(), infoImagesReq.getPageSize(),infoImagesRS);//.getMenuByAuthoritieId(principal.getName());
		modelMap.put("page",page);
		return new ModelAndView("image/list",modelMap);
	}
	@RequestMapping("/infoImagesQueryToSet")
	public ModelAndView  infoImagesQueryToSet(@ModelAttribute InfoImagesReq infoImagesReq, HttpServletRequest request,HttpServletResponse response, ModelMap modelMap){
		//super.adminLoginValidate(request);
		InfoImagesRS infoImagesRS=infoImagesReq.getInfoImagesRS();
		modelMap.put("pageSize",infoImagesReq.getPageSize());
		modelMap.put("pageNo", infoImagesReq.getPageNo());
		modelMap.put("ctx", request.getContextPath());
		modelMap.put("infoImagesRS", infoImagesRS);
		modelMap.put("bllId", infoImagesReq.getBllId());
		modelMap.put("bllType", infoImagesReq.getBllType());
		modelMap.put("bllFlag", infoImagesReq.getBllFlag());
		modelMap.put("bllBackUrl", infoImagesReq.getBllBackUrl());
		Page<InfoImages> page=infoImagesService.findInfoImagesByPage(infoImagesReq.getPageNo(), infoImagesReq.getPageSize(),infoImagesRS);//.getMenuByAuthoritieId(principal.getName());
		modelMap.put("page",page);
		return new ModelAndView("image/imagelist",modelMap);
	}
	
	@RequestMapping("/infoImagesSet")
	public ModelAndView  infoImagesSet(@ModelAttribute InfoImagesReq infoImagesReq, HttpServletRequest request,HttpServletResponse response, ModelMap modelMap){
		//super.adminLoginValidate(request);
		InfoImagesRS infoImagesRS= infoImagesReq.getInfoImagesRS();
		modelMap.put("infoImagesRS", infoImagesRS);
		
		if("infoNew".equals(infoImagesReq.getBllType())){
			String value=infoImagesReq.getValues().replaceAll(",", "");
			InfoImages  infoImage=infoImagesService.infoImagesGet(Long.parseLong(value));
			InfoNews infoNews=infoNewsService.infoNewsGet(Long.parseLong(infoImagesReq.getBllId()));
			infoNews.setImageUrl(infoImage.getImageUrl());
			infoNews.setImageId(infoImage.getId());
			infoNewsService.infoNewsUpdate(infoNews);
		}
		modelMap.put("callbackUrl", infoImagesReq.getBllBackUrl());
		return new ModelAndView("success",modelMap);
	}
	
	/**
	 *InfoImages打开新增界面
	 */
	@RequestMapping("/prepareInfoImagesAdd")
	public ModelAndView  prepareInfoImagesAdd(@ModelAttribute InfoImagesReq infoImagesReq, HttpServletRequest request,HttpServletResponse response, ModelMap modelMap){
		//super.adminLoginValidate(request);
		InfoImagesRS infoImagesRS= infoImagesReq.getInfoImagesRS();
		modelMap.put("infoImagesRS", infoImagesRS);
		return new ModelAndView("image/upload",modelMap);
	}
	@RequestMapping("/upload/images")
	public @ResponseBody Result uploadImage(@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request,ModelMap modelMap){
		//super.adminLoginValidate(request);
		
		System.out.println("开始");
		String  path =request.getSession().getServletContext().getRealPath("/upload/");
		path+="/image/";
		System.out.println(path);
		String fileName = file.getOriginalFilename();
		// String fileName = new Date().getTime()+".jpg";c
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		InfoImages infoImages=new InfoImages();
		// 保存
		try {
			file.transferTo(targetFile);
			infoImages.setCreateUser("test");
			infoImages.setCreateDate(new Date());
			String webPath=request.getSession().getServletContext().getContextPath();
			webPath+="/upload/image/"+fileName;
			infoImages.setImageUrl(webPath);
			infoImages.setName(fileName);
			infoImages.setIsUploadwx("0");
			infoImages.setRealUrl(path+fileName);
			infoImagesService.infoImagesSave(infoImages);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(infoImages.getId()!=null){
			String id=request.getParameter("businessId");
			String type=request.getParameter("businessType");
			if(!Strings.isNullOrEmpty(type)&&!Strings.isNullOrEmpty(id)){
				if("product".equals(type)){
					InfoProduct infoProduct=infoProductService.infoProductGet(Long.parseLong(id));
					InfoProductImage infoProductImage=new InfoProductImage();
					infoProductImage.setImagesId(infoImages.getId());
					infoProductImage.setProductId(infoProduct.getId());
					infoProductImageService.infoNewsSave(infoProductImage);
					if(Strings.isNullOrEmpty(infoProduct.getImageUrl())){
						infoProduct.setImageUrl(infoImages.getImageUrl());
						infoProductService.infoProductUpdate(infoProduct);
					}
				}else if("news".equals(type)){
					InfoNews infoNews =infoNewsService.infoNewsGet(Long.parseLong(id));
					infoNews.setImageUrl(infoImages.getImageUrl());
					infoNewsService.infoNewsUpdate(infoNews);
				}else if("productType".equals(type)){
					InfoProductType infoProductType =infoProductTypeService.infoProductTypeGet(Long.parseLong(id));
					infoProductType.setTypeImageUrl(infoImages.getImageUrl());
					infoProductTypeService.infoProductTypeUpdate(infoProductType);
				}
			}
		}
		modelMap.addAttribute("fileUrl", request.getContextPath() + "/upload/"+ fileName);
		Result r=new Result();
		r.setCode("1");
		r.setMessage("上传成功");
		return r;
	}
	@Autowired
	private InfoProductImageService infoProductImageService;
	@Autowired
	private InfoProductService infoProductService;

	@Autowired
	private InfoNewsService infoNewsService;

	@Autowired
	private InfoProductTypeService infoProductTypeService;

	/**
	 *InfoImages删除操作
	 */
	@RequestMapping("/infoImagesDelete")
	public  ModelAndView  infoImagesDelete(@ModelAttribute InfoImagesReq infoImagesReq, HttpServletRequest request,HttpServletResponse response, ModelMap modelMap){
		//super.adminLoginValidate(request);
		String message="操作成功   ";
		InfoImages infoImages=infoImagesReq.getInfoImages();
		infoImages=infoImagesService.infoImagesGet(infoImages.getId());
		if(infoImages.getRealUrl()!=null&&!"".equals(infoImages.getRealUrl())){
			File file=new File(infoImages.getRealUrl());
			if(file!=null&&file.exists()){
				file.delete();
				message+="本地文件删除成功";
			}
		}
		if("1".equals(infoImages.getIsUploadwx())){
			ApiResult r=MediaApi.delMaterial(infoImages.getWxMediaId());
			log.info(r.toString());
			message+="微信中删除成功";
		}

		infoImagesService.infoImagesDelete(infoImages);
		modelMap.put("message", message);
		modelMap.put("callbackUrl", "admin/infoImagesQuery");
		return new ModelAndView("success",modelMap);
	}
	/**
	 *InfoImages删除操作
	 */
	@RequestMapping("/infoImagesDeleteWeiXin")
	public  ModelAndView  infoImagesDeleteWeiXin(@ModelAttribute InfoImagesReq infoImagesReq, HttpServletRequest request,HttpServletResponse response, ModelMap modelMap){
		//super.adminLoginValidate(request);
		String message="";
		InfoImages infoImages=infoImagesReq.getInfoImages();
		infoImages=infoImagesService.infoImagesGet(infoImages.getId());
		if("1".equals(infoImages.getIsUploadwx())){
			ApiResult r=MediaApi.delMaterial(infoImages.getWxMediaId());
			Integer errorcode=r.getErrorCode();
			log.info(r.toString());
			if(errorcode==null||errorcode==0){

				message+="微信中删除成功";
				infoImages.setIsUploadwx("0");
				infoImages.setWxMediaId(null);
				infoImages.setWxUrl(null);
				infoImagesService.infoImagesUpdate(infoImages);
				modelMap.put("message", message);
				modelMap.put("callbackUrl", "admin/infoImagesQuery");
				return new ModelAndView("success",modelMap);
			}else{

				message+="微信中删除失败";
				modelMap.put("message", message);
				modelMap.put("callbackUrl", "admin/infoImagesQuery");
				return new ModelAndView("error",modelMap);
			}
			
		}else{

			message+="未上传至微信，无需删除";
			modelMap.put("message", message);
			modelMap.put("callbackUrl", "admin/infoImagesQuery");
			return new ModelAndView("error",modelMap);
		}
	}
	
	
	/**
	 *InfoImages删除操作
	 */
	@RequestMapping("/infoImagesUploadWeiXin")
	public  ModelAndView  infoImagesUploadWeiXin(@ModelAttribute InfoImagesReq infoImagesReq, HttpServletRequest request,HttpServletResponse response, ModelMap modelMap){
		//super.adminLoginValidate(request);
		
		InfoImages infoImages=infoImagesReq.getInfoImages();
		infoImages=infoImagesService.infoImagesGet(infoImages.getId());
		
		if("1".equals(infoImages.getIsUploadwx())){
			modelMap.put("callbackUrl", "admin/infoImagesQuery");
			modelMap.put("message", "已经上传了微信，不能重复上传");
			return new ModelAndView("error",modelMap);
		}
		
		if(infoImages.getRealUrl()!=null&&!"".equals(infoImages.getRealUrl())){
			File file=new File(infoImages.getRealUrl());
			if(file!=null&&file.exists()){
				ApiResult r=MediaApi.addMaterial(file, "图片", "图片");
				Integer errcode=r.getErrorCode();
				log.info(r.toString());
				if(errcode==null||"".equals(errcode)){

					String media_id=r.getStr("media_id");
					String url=r.getStr("url");
					infoImages.setIsUploadwx("1");
					infoImages.setWxMediaId(media_id);
					infoImages.setWxUrl(url);
					infoImagesService.infoImagesUpdate(infoImages);
					modelMap.put("callbackUrl", "admin/infoImagesQuery");
					modelMap.put("message", "成功上传到微信");
					return new ModelAndView("success",modelMap);
				}else{
					String errmsg=r.getStr("errmsg");
					modelMap.put("callbackUrl", "admin/infoImagesQuery");
					modelMap.put("message", "错误代码："+errcode+"，信息："+errmsg);
					return new ModelAndView("error",modelMap);
				}
			}else{


				modelMap.put("callbackUrl", "admin/infoImagesQuery");
				modelMap.put("message", "找不到文件的路径");
				return new ModelAndView("error",modelMap);
			}
		}else{

			modelMap.put("callbackUrl", "admin/infoImagesQuery");
			modelMap.put("message", "找不到文件的路径");
			return new ModelAndView("error",modelMap);
		}

		
	}
}
